package cn.sylinx.horm.spring.boot;

import javax.sql.DataSource;

import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import cn.sylinx.horm.core.SqlClient;
import cn.sylinx.horm.util.GLog;
import org.springframework.lang.NonNull;

@Configuration
@ConditionalOnProperty(prefix = "horm", name = "enable", havingValue = "true", matchIfMissing = true)
@Conditional(SqlClientUseSpringCondition.class)
@ConditionalOnBean(DataSource.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@EnableConfigurationProperties(HORMBootConfig.class)
@Import({ AutoConfiguredCommandScannerRegistrar.class, AutoConfiguredModelScannerRegistrar.class,
        AutoConfiguredMapperScannerRegistrar.class })
public class SqlClientInSpringAutoConfiguration implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Bean
    @ConditionalOnMissingBean
    public SqlClient sqlClientInSpring(HORMBootConfig bootConfig) {
        GLog.debug("SqlClient[UseSpring] inited begin..");
        SqlClient sqlClient = new SqlClientInitBySpring().setApplicationContext(applicationContext)
                .setBootConfig(bootConfig).create();
        GLog.info("SqlClient[UseSpring] inited done");
        return sqlClient;
    }
}